<template>
  <view class="add-friend-container">
    <!-- 搜索好友 -->
    <view class="search-section">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索用户ID、邮箱或用户名..." 
          v-model="searchKeyword"
          @input="handleSearch"
        />
      </view>
      <button class="search-btn" @click="searchUsers" :disabled="isSearching">
        {{ isSearching ? '搜索中...' : '搜索' }}
      </button>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="searchHistory.length > 0">
      <view class="section-title">
        <text class="title-text">搜索历史</text>
        <text class="clear-btn" @click="clearHistory">清空</text>
      </view>
      <view class="history-list">
        <view 
          v-for="item in searchHistory" 
          :key="item.id"
          class="history-item"
          @click="searchByHistory(item)"
        >
          <text class="history-text">{{ item.keyword }}</text>
          <text class="history-time">{{ formatTime(item.time) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <view class="section-title">
        <text class="title-text">搜索结果</text>
        <text class="result-count">({{ searchResults.length }})</text>
      </view>
      <view class="result-list">
        <view 
          v-for="user in searchResults" 
          :key="user.id"
          class="result-item"
        >
          <view class="user-avatar-section">
            <image 
              v-if="user.avatar" 
              :src="user.avatar" 
              class="user-avatar"
              mode="aspectFill"
            />
            <view v-else class="default-avatar">
              <text class="avatar-text">{{ user.name.charAt(0) }}</text>
            </view>
          </view>
          
          <view class="user-info">
            <text class="user-name">{{ user.name }}</text>
            <text class="user-id">ID: {{ user.id }}</text>
            <text class="user-desc">{{ user.description || '这个人很懒，什么都没写' }}</text>
          </view>
          
          <view class="user-actions">
            <button 
              v-if="user.status === 'none'"
              class="add-btn" 
              @click="addFriend(user)"
              :disabled="isAdding"
            >
              添加
            </button>
            <button 
              v-else-if="user.status === 'pending'"
              class="pending-btn" 
              disabled
            >
              已发送
            </button>
            <button 
              v-else-if="user.status === 'accepted'"
              class="accepted-btn" 
              disabled
            >
              已是好友
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!searchKeyword && searchResults.length === 0" class="empty-state">
      <text class="empty-icon">👥</text>
      <text class="empty-text">搜索用户ID、邮箱或用户名来添加好友</text>
    </view>
    
    <!-- 二维码扫描 -->
    <view class="qr-section">
      <view class="qr-card" @click="scanQRCode">
        <text class="qr-icon">📱</text>
        <text class="qr-text">扫描二维码添加好友</text>
      </view>
    </view>
    
    <!-- 我的二维码 -->
    <view class="my-qr-section">
      <view class="my-qr-card" @click="showMyQRCode">
        <text class="qr-icon">📄</text>
        <text class="qr-text">我的二维码</text>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import appStateManager from '@/utils/app-state-manager.js'

export default {
  data() {
    return {
      searchKeyword: '',
      isSearching: false,
      isAdding: false,
      searchResults: [],
      searchHistory: []
    }
  },
  
  onLoad() {
    // 使用新的状态管理器
    appStateManager.subscribe('server', (serverState) => {
      this.isServerOnline = serverState.isOnline
    })
  },
  
  methods: {
    // 加载搜索历史（简化版）
    loadSearchHistoryIfOnline() {
      if (this.isServerOnline) {
        this.loadSearchHistory()
      }
    },
    
    handleSearch() {
      // 实时搜索逻辑
      if (this.searchKeyword.length > 2) {
        this.searchUsers()
      }
    },
    
    async searchUsers() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }
      
      this.isSearching = true
      
      try {
        // 调用真实API搜索用户
        const result = await apiService.searchUsers(this.searchKeyword)
        
        // 处理搜索结果
        if (result && result.data && result.data.length > 0) {
          this.searchResults = result.data.map(user => ({
            id: user.id, // 确保使用数字类型的用户ID
            name: user.name || user.email,
            email: user.email,
            avatar: user.avatar || '',
            description: user.bio || '这个人很懒，什么都没写',
            status: this.getUserFriendStatus(user)
          }))
        } else {
          this.searchResults = []
          uni.showToast({
            title: '未找到相关用户',
            icon: 'none'
          })
        }
        
        // 添加到搜索历史
        this.addToHistory(this.searchKeyword)
        
      } catch (error) {
        console.error('搜索用户失败:', error)
        
        // 如果是在线模式失败，显示错误信息
        if (!error.message || !error.message.includes('离线模式')) {
          uni.showToast({
            title: '搜索失败，请重试',
            icon: 'error'
          })
        } else {
          // 离线模式，使用本地数据搜索
          this.searchLocalUsers()
        }
      } finally {
        this.isSearching = false
      }
    },
    
    // 获取用户好友状态
    getUserFriendStatus(user) {
      // 这里可以根据实际的好友关系数据来判断状态
      // 暂时返回 'none'，表示可以添加
      return 'none'
    },
    
    // 本地搜索用户（离线模式）
    searchLocalUsers() {
      try {
        const users = JSON.parse(uni.getStorageSync('users') || '[]')
        const keyword = this.searchKeyword.toLowerCase()
        
        const filteredUsers = users.filter(user => {
          const name = (user.name || '').toLowerCase()
          const email = (user.email || '').toLowerCase()
          return name.includes(keyword) || email.includes(keyword)
        })
        
        this.searchResults = filteredUsers.map(user => ({
          id: user.id, // 确保使用数字类型的用户ID
          name: user.name || user.email,
          email: user.email,
          avatar: user.avatar || '',
          description: user.bio || '这个人很懒，什么都没写',
          status: 'none'
        }))
        
        if (this.searchResults.length === 0) {
          uni.showToast({
            title: '未找到相关用户（离线模式）',
            icon: 'none'
          })
        }
        
        // 添加到搜索历史
        this.addToHistory(this.searchKeyword)
        
      } catch (error) {
        console.error('本地搜索失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'error'
        })
      }
    },
    
    addToHistory(keyword) {
      const existingIndex = this.searchHistory.findIndex(item => item.keyword === keyword)
      if (existingIndex !== -1) {
        this.searchHistory.splice(existingIndex, 1)
      }
      
      this.searchHistory.unshift({
        id: Date.now(),
        keyword: keyword,
        time: new Date().toISOString()
      })
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }
      
      this.saveSearchHistory()
    },
    
    searchByHistory(item) {
      this.searchKeyword = item.keyword
      this.searchUsers()
    },
    
    clearHistory() {
      uni.showModal({
        title: '清空历史',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = []
            this.saveSearchHistory()
          }
        }
      })
    },
    
    async addFriend(user) {
      this.isAdding = true
      
      try {
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          uni.showToast({
            title: '用户未登录',
            icon: 'error'
          })
          return
        }

        const userData = JSON.parse(currentUser)
        
        console.log('当前用户数据:', userData)
        console.log('目标用户数据:', user)
        
        // 检查用户ID是否存在
        if (!userData.id) {
          uni.showToast({
            title: '用户信息不完整，请重新登录',
            icon: 'error'
          })
          return
        }
        
        const toUserId = parseInt(user.id)
        
        console.log('发送好友请求参数:', {
          fromUserId: userData.id,
          toUserId: toUserId,
          fromUserIdType: typeof userData.id,
          toUserIdType: typeof toUserId
        })
        
        if (isNaN(toUserId)) {
          uni.showToast({
            title: '目标用户ID无效',
            icon: 'error'
          })
          return
        }
        
        // 调用API发送好友请求
        try {
          const response = await apiService.sendFriendRequest(userData.id, toUserId, '我想加你为好友')
          if (response.code === 'SUCCESS') {
            console.log('服务器发送好友请求成功')
          }
        } catch (error) {
          console.log('服务器发送好友请求失败，仅本地保存:', error)
        }
        
        // 更新用户状态
        user.status = 'pending'
        
        // 保存好友请求到本地
        this.saveFriendRequest(user, userData)
        
        uni.showToast({
          title: '好友请求已发送',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('发送好友请求失败:', error)
        uni.showToast({
          title: '发送失败，请重试',
          icon: 'error'
        })
      } finally {
        this.isAdding = false
      }
    },
    
    saveFriendRequest(user, currentUserData) {
      try {
        // 按用户ID保存好友请求数据
        const userRequestsData = uni.getStorageSync(`friend_requests_${currentUserData.id}`) || '{"sent": [], "received": []}'
        const userRequests = JSON.parse(userRequestsData)
        
        const newRequest = {
          id: Date.now(),
          fromUser: {
            id: currentUserData.id,
            name: currentUserData.name,
            email: currentUserData.email,
            avatar: currentUserData.avatar
          },
          toUser: user,
          status: 'pending',
          createTime: new Date().toISOString(),
          message: '我想加你为好友'
        }
        
        userRequests.sent.push(newRequest)
        uni.setStorageSync(`friend_requests_${currentUserData.id}`, JSON.stringify(userRequests))
        
      } catch (error) {
        console.error('保存好友请求失败:', error)
      }
    },
    
    scanQRCode() {
      uni.showToast({
        title: '扫码功能开发中',
        icon: 'none'
      })
    },
    
    showMyQRCode() {
      uni.showModal({
        title: '我的二维码',
        content: '二维码功能开发中，敬请期待！',
        showCancel: false
      })
    },
    
    
    loadSearchHistory() {
      try {
        const history = uni.getStorageSync('search_history')
        if (history) {
          this.searchHistory = JSON.parse(history)
        }
      } catch (error) {
        console.error('加载搜索历史失败:', error)
      }
    },
    
    saveSearchHistory() {
      try {
        uni.setStorageSync('search_history', JSON.stringify(this.searchHistory))
      } catch (error) {
        console.error('保存搜索历史失败:', error)
      }
    },
    
    formatTime(time) {
      const now = new Date()
      const targetTime = new Date(time)
      const diff = now - targetTime
      
      if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return targetTime.toLocaleDateString()
      }
    }
  }
}
</script>

<style scoped>
.add-friend-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
}

/* 搜索区域 */
.search-section {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: white;
  border-radius: 25rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
  color: #999;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  border: none;
  outline: none;
}

.search-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 25rpx;
  padding: 20rpx 30rpx;
  font-size: 26rpx;
  min-width: 120rpx;
}

.search-btn:disabled {
  background: #ccc;
}

/* 搜索历史 */
.search-history {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.clear-btn, .refresh-btn {
  font-size: 24rpx;
  color: #667eea;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.history-text {
  font-size: 26rpx;
  color: #333;
}

.history-time {
  font-size: 22rpx;
  color: #999;
}

/* 搜索结果 */
.search-results {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.result-count {
  font-size: 22rpx;
  color: #999;
  margin-left: 8rpx;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.user-avatar-section {
  margin-right: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.default-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  color: white;
  font-size: 32rpx;
  font-weight: bold;
}

.user-info {
  flex: 1;
}

.user-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.user-id {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.user-desc {
  display: block;
  font-size: 22rpx;
  color: #999;
}

.user-actions {
  margin-left: 20rpx;
}

.add-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

.pending-btn {
  background: #f39c12;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

.accepted-btn {
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80rpx 20rpx;
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.empty-icon {
  display: block;
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

/* 二维码功能 */
.qr-section, .my-qr-section {
  margin-bottom: 20rpx;
}

.qr-card, .my-qr-card {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.qr-card:active, .my-qr-card:active {
  transform: scale(0.98);
}

.qr-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.qr-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
</style>
